package com.cetool.autocms.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.cetool.autocms.enumeration.SystemExceptionEnum;
import com.cetool.autocms.exception.ServiceException;
import com.cetool.autocms.pojo.domain.login.UserInfoDO;

import java.util.Date;

/**
 * token工具类
 *
 * @author 戴越
 * @date 2021/11/9
 */
public final class TokenUtil {

    /**
     * token到期时间10小时
     */
    private static final long EXPIRE_TIME = 10 * 60 * 60 * 1000;

    /**
     * 密钥
     */
    private static final String TOKEN_SECRET = "ljdyaishijin**3nkjnj??";

    /**
     * 私有化构造器
     */
    private TokenUtil() {
    }

    /**
     * 生成token
     *
     * @param userName 用户名称
     * @return java.lang.String
     * @author 戴越
     * @date 2021/11/9
     */
    public static String createToken(String userName) {
        //获取当前时间
        Date now = DateUtil.date();
        Date expireTime = DateUtil.date(now.getTime() + EXPIRE_TIME);
        return JWT.create().withIssuedAt(now).withExpiresAt(expireTime).withAudience(userName)
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
    }

    /**
     * 生成token
     *
     * @param user 用户实体
     * @return java.lang.String
     * @author 戴越
     * @date 2021/11/9
     */
    public static String createToken(UserInfoDO user) {
        //获取当前时间
        Date now = DateUtil.date();
        Date expireTime = DateUtil.date(now.getTime() + EXPIRE_TIME);
        return JWT.create().withIssuedAt(now).withExpiresAt(expireTime).withAudience(user.getUserName())
                //自定义字段存数据
                .withClaim("data", JSONUtil.toJsonStr(user))
                .sign(Algorithm.HMAC256(TOKEN_SECRET));
    }

    /**
     * 检验token是否有效
     *
     * @param token
     * @return java.lang.Boolean
     * @author 戴越
     * @date 2021/11/9
     */
    public static Boolean verifyToken(String token) {
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
            verifier.verify(token);
            return true;
        } catch (JWTVerificationException jwtVerificationException) {
            throw new ServiceException(SystemExceptionEnum.USER_TOKEN_FAILURE_EXCEPTION);
        }
    }
}
